/**
 * Created by kouen on 2017/8/28.
 */

import * as echarts from "echarts";

/**
 * 配置参数设置，常量
 * @type {{PageSize: number, PageNumber: number, SortName: string, SortOrder: string, Cols: [*]}}
 */
const Default = {
    PageSize: 10,
    PageNumber: 1,
    SortName: "time",
    SortOrder: "desc",
    Cols: [
        {
            title: "时间",
            field: "time",
            align: "center",
            valign: "middle",
            sortable: true,
        },
        {
            title: "股票",
            field: "stock",
            align: "center",
            valign: "middle",
            sortable: true
        },
        {
            title: "指标",
            field: "quota",
            align: "center",
            valign: "middle",
            sortable: true,
            formatter:function(value,row,index){
                let buttons = [];
                for (let i in value){
                    if (value.hasOwnProperty(i) && value[i] !== 'None'){
                        buttons.push(`<div class="btn btn-sm" style="border: 1px dashed #ccc;">${i}:${value[i]}</div>`);
                    }
                }
                return `<div class="btn-group">${buttons.join('\n')}</div>`
            }
        },
        {
            title: "通过率",
            field: "pass",
            align: "center",
            valign: "middle",
            sortable: true,
            formatter:function(value,row,index){
                if (value >= 80)
                    return `<div class="btn" style="background-color: #ffffff; color: #000000;">${value}%</div>`;
                else if (value >= 60)
                    return `<div class="btn" style="background-color: #bcbcbc; color: #FFFFFF;">${value}%</div>`;
                else if (value >= 40)
                    return `<div class="btn" style="background-color: #848484; color: #FFFFFF;">${value}%</div>`;
                else if (value >= 20)
                    return `<div class="btn" style="background-color: #434343; color: #FFFFFF;">${value}%</div>`;
                else
                    return `<div class="btn" style="background-color: #000000; color: #FFFFFF;">${value}%</div>`;
            }
        }
    ],
    Params: args => {
        return args;
    },
};

/**
 * 初始化首页的数据，包括汇总的两个表格和当前概况
 */
{
    FlushTable();
    fetch("/config/market/" , {
        method: 'POST',
        headers: {'Accept': 'application/json', 'Content-Type': 'application/json'},
        body: '',  //即传入字符串data={....}
    }).then((res)=>{
        if (res.status === 200){
            return res
        }
    }).then((data)=>{
        data.json().then((obj)=>{
            $("#market").css("display", "inline");
            ShowPie('chart_market_1', ToPieData(obj.data.mcap), 'mcap', '流程市值(亿)');
            ShowPie('chart_market_2', ToPieData(obj.data.turnover), 'turnover', '换手率');
            ShowPie('chart_market_3', ToPieData(obj.data.voturnover), 'voturnover', '成交量(亿)');
            ShowPie('chart_market_4', ToPieData(obj.data.vaturnover), 'vaturnover', '成交金额(亿)');
        });
    }).catch(()=>{
        console.log("初始化首页数据出现错误");
        $("#market").css("display", "none");
    });
}


/**
 初始化Table的列,并且初始化数据
 * @param tableID 表的ID
 * @param parse 参数的函数
 * @param columns 列的描述数据列表
 * @param fatherID 父控件的名称
 */
function initTable(tableID, columns, parse, fatherID='DataTable') {
    let father = $(`#${fatherID}`);
    father[0].innerHTML = `<table id="${tableID}"></table>`;

    let name = $(".strategy_check")[0].innerText;
    $(`#${tableID}`).bootstrapTable({
        method: 'GET',
        toolbar: `#toolbar`, //工具按钮用哪个容器
        cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        showRefresh: true,
        pagination: true, //是否显示分页（*）
        sortable: true, //是否启用排序
        sortOrder: Default.SortOrder, //排序方式
        sortName: Default.SortName,
        pageNumber: Default.PageNumber, //初始化加载第一页，默认第一页
        pageSize: Default.PageSize, //每页的记录行数（*）
        url: `/config/query/page/?name=${name}`, //这个接口需要处理bootstrap table传递的固定参数
        queryParamsType: '', //默认值为 'limit' ,在默认情况下 传给服务端的参数为：offset,limit,sort 设置为 '' 在这种情况下传给服务器的参数为：pageSize,pageNumber
        sidePagination: "server",
        minimumCountColumns: 2,
        clickToSelect: true,
        search: true,
        searchOnEnterKey: true,
        columns: columns,
        paginationVAlign: 'top',
        pageList: [10],
        queryParams: parse
    });
}


/**
 * 根据name_text判断读取哪张表，同时请求接口或者数据库数据
 *  1. 相应单机命令，切换数据到控件上（名称，公式）
 *  2. 更改按钮名称和修改按钮功能为(保存、清空、删除)
 */
function FlushTable(query_name=''){
    $.get(`/config/query/strategy/?query=${query_name}`, (res)=>{

        let table = $("#table_item");
        table[0].innerHTML = '';
        for (let item of res){
            table.append(`<button id="table_btn_${item.id}" style="width: 100%; border:0; background-color: #FFF" value="${item.formula.join('\n')}">${item.name}</button>`)
            $("#table_btn_" + item.id).click((e)=>{
                for (let i of $("#table_item").children()){
                    $(`#${i.id}`).removeClass('strategy_check');
                }
                $(`#${e.currentTarget.id}`).addClass('strategy_check');

                initTable('strategy_table', Default.Cols, Default.Params);

                let formula = e.currentTarget.value.split('\n');
                let sub_divs = '';
                let pos = 1;
                for (let i of formula){
                    sub_divs += `<button id="formula_btn_${pos}" style="outline:none;border-radius: 5px; border: 1px dashed #aaa; margin-left: 3px; margin-top: 3px; background-color: #FFFFFF; color: #000000;">${i}</button>`
                    pos += 1;
                }
                $("#strategy_formula")[0].innerHTML = `<div class="btn-group">${sub_divs}</div>`;
                $("button[id^=formula_btn]").click(e=>{
                    let self = $(`#${e.currentTarget.id}`);
                    if (self.hasClass('check')){
                        self.removeClass('check');
                        self.css({
                            backgroundColor: '#FFFFFF',
                            color: '#000000'
                        });
                    }else{
                        self.addClass('check');
                        self.css({
                            backgroundColor: '#30b3ff',
                            color: '#ffffff'
                        });
                    }

                    let formula = [];
                    for (let i of $('button[class=check]'))
                        formula.push(i.innerText);

                    let table = $("#strategy_table");

                    table.bootstrapTable('destroy');
                    initTable('strategy_table', Default.Cols, args=>{
                        args.formula = formula;
                        return args;
                    });
                });
            })
        }
    });
}


function ToPieData(data){
    let series = [];
    let label = [];
    for (let industry in data){
        label.push(industry);
        series.push({value: data[industry], name: industry});
    }
    return {series:series, label:label}
}

function ShowPie(div, data, name, title) {
    let myChart = echarts.init(document.getElementById(div));
    let option = {
        title: {
            text: title,
            left: 'center'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: data.label,
            selected: data.label
        },
        series : [
            {
                name: name,
                type: 'pie',
                radius : '55%',
                center: ['40%', '50%'],
                data: data.series,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };
    myChart.setOption(option);
    myChart.on('click', function (params) {
        $.post(
            "/config/market_detail/",
            {
                st: $("#detail_st").val(),
                ed: $("#detail_ed").val(),
                field: params.seriesName,
                industry: params.name
            },
            (res)=>{
                $("#detail_market").css("display", "inline");
                ShowMultiLineChart("detail_chart", res.xAxis, res.yAxis, res.name, res.field);
            }
        );
    });
}


function ShowMultiLineChart(chart_id, xAxis, yAxis, name, field){
    let myChart = echarts.init(document.getElementById(chart_id));
    let option = myChart.getOption();
    myChart.clear();
    if (option === undefined || option.title[0].text !== field){
        option = {
            title: {
                text: field
            },
            tooltip: {
                trigger: 'axis'
            },
            legend: {
                data:[name]
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            toolbox: {
                feature: {
                    saveAsImage: {}
                }
            },
            xAxis: {
                type: 'category',
                data: xAxis
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: name,
                data: yAxis,
                type: 'line',
                smooth: true
            }]
        };
    }else{
        let n_yAxis = [],
            n_label = [];
        if (option.legend[0].data.indexOf(name) === -1){
            option.legend[0].data.push(name);
            option.series.push({
                name: name,
                data: yAxis,
                type: 'line',
                smooth: true
            });
        }else{
            for (let index in option.legend[0].data){
                if (option.legend[0].data[index] !== name){
                    n_label.push(option.legend[0].data[index]);
                    n_yAxis.push(option.series[index])
                }
            }
            option.legend[0].data = n_label;
            option.series = n_yAxis;
        }
        option.xAxis[0].data = xAxis;
    }
    myChart.setOption(option);
}